<?php
defined('SYSPATH') or die('No direct script access.') ;

define('ETAO_SITE_URL','http://resource.360hqb.com');
/**
 * @author Y.N
 *  2011/5/9
 */
class Cli_Etao extends CLI
{
	protected static $_path = Null;

	public function main()
	{
		header('Content-type: application/xml; charset=utf-8');

		self::$_path = RESPATH.'etao/';

		// 增量删除
		self::deleted_xml();

		// 全量索引
		self::make_spu_full_xml();

		// 商品类目
		self::make_cat_xml();

	}

	/**
	 * 删除已下架商品
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/8/24
	 */
	public static function deleted_xml()
	{
		// 获取上一次全量索引
		$file_dat = self::$_path.'last_outer.dat';

		if (file_exists($file_dat))
		{
			$last_out_goods = unserialize(file_get_contents($file_dat));
		}

		$xml = '<?xml version="1.0" encoding="utf-8"?>';
		$xml .= '<root><version>1.0</version>';
		$xml .= '<modified>'.date('Y-m-d H:i:s').'</modified>';
		$xml .= '<seller_id>华强北在线官网</seller_id>';
		$xml .= '<cat_url>'.ETAO_SITE_URL.'/etao/SellerCats.xml</cat_url>';
		$xml .= '<item_ids>';

		if ( ! empty($last_out_goods))
		{
			foreach ($last_out_goods as $goods_id)
			{
				// 查询是否下架或删除
				$goods_info = DB::select('shop_id', 'deleted', 'on_sale')
					->from('goods')
					->where('goods_id', '=', $goods_id)
					->fetch_row();

				// 查询是否存在消保
				$protections = DB::select('cert_type')
					->from('shops')
					->where('shop_id', '=', $goods_info['shop_id'])
					->where('deleted', '=', 0)
					->where('status', '=', 4)
					->fetch_one();

				if ($goods_info['deleted'] OR ! $goods_info['on_sale'] OR empty($protections))
				{
					$xml .= '<outer_id action="delete">'.$goods_id.'</outer_id>';

					$file = self::$_path.'items/'.$goods_id.'.xml';
					if (file_exists($file))
					{
						@unlink($file);
					}
				}
			}
		}
		$xml .= '</item_ids></root>';

		$increment_file = self::$_path.'IncrementIndex.xml';
		file_put_contents($increment_file, $xml);

		CLI::output("\n增量完毕\n");
	}


	/**
	 * 生成SPU页面
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/10/28
	 */
	public static function make_spu_full_xml()
	{
		$item_url = "http://item.360hqb.com/";

		$last_out_goods = array();
		$google_goods = array();

		$products = DB::select('product_id')
			->from('products')
			->where('status', '=', 3)
			->fetch_all();

		$xml = '<?xml version="1.0" encoding="utf-8" ?>';
		$xml .= '<root>';
			$xml .='<version>1.0</version>';
			$xml .= '<modified>'.date('Y-m-d H:i:s').'</modified>';
			$xml .= '<seller_id>华强北在线官网</seller_id>';
			$xml .= '<cat_url>'.ETAO_SITE_URL.'/etao/SellerCats.xml</cat_url>';
			$xml .= '<dir>'.ETAO_SITE_URL.'/etao/items/</dir>';
			$xml .= '<item_ids>';

		$youdao = "商品名称,链接地址,图片地址,销售价格,商品描述,图书 ISBN,库存状态,商品品牌,商品分类,有道第一级分类\r\n";

		foreach ($products as $p)
		{
			$item_ids = NULL;
			try
			{
				// java接口获取商品数据
				$response = new Spu_Search($p['product_id']);
				$spu_search = $response->get_response();
				if ($spu_search)
				{
					$item_ids = $spu_search->get_item_ids();
				}

				if ( ! empty($item_ids))
				{
					$ids = explode(',', $item_ids);
					foreach ($ids as $k => $goods_id)
					{
						$value = DB::select('goods_id', 'shop_id', 'retail_price', 'cid', 'goods_title', 'image_md5', 'freight_id', 'props_str', 'stock')
							->from('goods')
							->where('deleted', '=', 0)
							->where('goods_id', '=', $goods_id)
							->fetch_row();
						$xml .= '<outer_id action="upload">'.$goods_id.'</outer_id>';

						$last_out_goods[] = $value['goods_id'];

						// 生成单个商品xml
						$return = self::make_goods_xml($value, $item_url, $p['product_id'], $k);
						// 生成有道csv
						$youdao .= implode(",",$return)."\r\n";
						$google_goods[] = $value;
					}
				}
			} catch(Exception $e) {
				sleep(3);
			}
		}
		$on_sale_goods = DB::select('goods_id', 'shop_id', 'retail_price', 'cid', 'goods_title', 'image_md5', 'freight_id', 'props_str', 'stock')
			->from('goods')
			->where('deleted', '=', 0)
			->where('on_sale', '=', 1)
			->where('expire_time', '>', time())
			->fetch_all();

		foreach ($on_sale_goods as $value)
		{
			// 是否有消保
			$protection = DB::select('cert_type')
				->from('shops')
				->where('shop_id', '=', $value['shop_id'])
				->where('deleted', '=', 0)
				->where('status', '=', 4)
				->fetch_one();

			if ( ! empty($protection))
			{

				$last_out_goods[] = $value['goods_id'];
				$xml .= '<outer_id action="upload">'.$value['goods_id'].'</outer_id>';

				$google_goods[] = $value;
				// 生成单个商品xml
				$return = self::make_goods_xml($value, $item_url);
				// 生成有道csv
				$youdao .= implode(",", $return)."\r\n";
			}
		}

		// 生成有道csv开始
		$date = date('ymd');
		$youdao_file = self::$_path.'youdao/360hqb'.$date.'.csv';
		$youdao = mb_convert_encoding($youdao, "gbk", "utf-8");
		file_put_contents($youdao_file, $youdao);
		// 生成有道csv结束

		$xml .= '</item_ids>';
		$xml .= '</root>';

		$file = self::$_path.'FullIndex.xml';
		file_put_contents($file, $xml);

		// 生成谷歌商品xml
		self::make_google_xml($google_goods, $item_url);

		// 保存历史商品dat:将本次所有的商品写入last_outer.dat中保存
		$file_dat = self::$_path.'last_outer.dat';
		file_put_contents($file_dat, serialize($last_out_goods));

		CLI::output("\n商品全量索引文件生成成功\n");
	}


	/**
	 * 生成商品文件
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/8/17
	 */
	public static function make_goods_xml($value, $item_url, $product_id = NULL, $key = NULL)
	{
		$cat_path = DB::select('cat_path')
			->from('item_cats')
			->where('cid', '=', $value['cid'])
			->fetch_one();

		if (substr_count($cat_path, ';') >= 3)
		{
			$explode = explode(';', $cat_path);
			$value['cid'] = next($explode);
		}

		//  获取运费
		$default_fee = DB::select('default_fee')
			->from('freight_tpls')
			->where('freight_id', '=', $value['freight_id'])
			->fetch_one();

		//  类目面包屑
		$cat_path = DB::select('cat_path')
				->from('item_cat_map')
				->where('cid', '=', $value['cid'])
				->fetch_one();
		$cat_map =  ! empty($cat_path) ? Cats_Map::get_map_path($cat_path) : array();
		$cat_array = array();
		foreach ($cat_map as $cat)
		{
				$cat_array[] = $cat['title'];
		}
		$cat_road = implode('>>', $cat_array);

		// seo
		preg_match_all('/(品牌:[^;]+)|([^;]*型号[^:]*:[^;]+)/', $value['props_str'], $matches);
		if ( is_array($matches[0]))
		{
            $words = array('b' => array(), 's' => NULL);
            foreach ($matches[0] as $match)
			{
                if (stristr($match, '品牌') !== FALSE)
				{
                    list( , $words['b']) = explode(':', $match);
                    $words['b'] = explode('/', $words['b']);
                } elseif (stristr($match, '型号') !== FALSE) {
                    list( , $words['s']) = explode(':', $match);
                }
            }
            $main_name = implode('/', $words['b']).' '.$words['s'];
        }

		// 有道CSV开始
		$goods_title = preg_replace("/(\,|\"|\')/", '', $value['goods_title']);
		$goods_data = array();
		$goods_data[] = $goods_title;
		if ($product_id)
		{
			$goods_data[] = $item_url.'spu-'.$product_id.'-'.($key+1).'.html';
		} else {
		    $goods_data[] = $item_url.$value['goods_id'].'.html';
		}

		$goods_data[] = URL::image($value['image_md5'],'160','product');
		$goods_data[] = $value['retail_price'];
		$goods_data[] = $main_name.' '.$goods_title;
		$goods_data[] = '';
		$goods_data[] = $value['stock'];
		$goods_data[] = implode('/', $words['b']);
		$goods_data[] = $cat_road;
		$goods_data[] = "电脑数码";
        // 有道CSV结束

		$pxml = '<?xml version="1.0" encoding="utf-8"?>';
		$pxml .= '<item>';
		$pxml .= '<seller_id>华强北在线官网</seller_id>';
		$pxml .= '<outer_id>'.$value['goods_id'].'</outer_id>';
		$pxml .= '<title><![CDATA['.$value['goods_title'].']]></title>';
		$pxml .= '<type>fixed</type>';
		$pxml .= '<price>'.$value['retail_price'].'</price>';
		$pxml .= '<image>'.URL::image($value['image_md5'],'160','product').'</image>';
		$pxml .= '<tags>'.$main_name.$value['goods_title'].'</tags>';
		$pxml .= '<scids>'.$value['cid'].'</scids>';
		$pxml .= '<post_fee>'.$default_fee.'</post_fee>';
		$pxml .= '<showcase>true</showcase>';
		if ($product_id)
		{
			$pxml .= '<href>'.$item_url.'spu-'.$product_id.'-'.($key+1).'.html</href>';
		} else {
		    $pxml .= '<href>'.$item_url.$value['goods_id'].'.html</href>';
		}
		$pxml .= '</item>';
		$file = self::$_path.'items/'.$value['goods_id'].'.xml';
		file_put_contents($file, $pxml);
		unset($pxml);
		return $goods_data;
		CLI::output(">");
	}


	/**
	 *生成目录
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/8/17
	 */
	public static function make_cat_xml()
	{
		$item_cats = DB::select('cid', 'name')
			->from('item_cats')
			->where('deleted', '=', 0)
			->where('parent_cid', '=', 0)
			->fetch_all();
		$catxml = '<?xml version="1.0" encoding="utf-8"?>';
		$catxml .= '<root>';
			$catxml .= '<version>1.0</version>';
			$catxml .= '<modified>'.date('Y-m-d H:i:s').'</modified>';
			$catxml .= '<seller_id>华强北在线官网</seller_id>';
			$catxml .= '<seller_cats>';
		foreach ($item_cats as $cat)
		{
			$catxml.='<cat>';
				$catxml.='<scid>'.$cat['cid'].'</scid>';
				$catxml.='<name><![CDATA['.$cat['name'].']]></name>';
				$catxml.='<cats>';
				$sub_cats = DB::select('cid', 'name')
					->from('item_cats')
					->where('deleted', '=', 0)
					->where('parent_cid', '=', $cat['cid'])
					->fetch_all();
				foreach($sub_cats as $sub_cat)
				{
					$catxml.='<cat>';
						$catxml.='<scid>'.$sub_cat['cid'].'</scid>';
						$catxml.='<name><![CDATA['.$sub_cat['name'].']]></name>';
					$catxml.='</cat>';
				}
				$catxml.='</cats>';
			$catxml.='</cat>';
			unset($sub_cats); unset($sub_cat);
		}
		$catxml .= '</seller_cats>';
		$catxml .= '</root>';

		$file = self::$_path.'SellerCats.xml';

		file_put_contents($file, $catxml);

		CLI::output("\n商品类目文件生成成功\n");
	}

	/**
	 * 谷歌XML
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/9/5
	 */
	public static function make_google_xml($goods, $item_url)
	{
		$length = 2000;
		for ($i=0; $i<20; $i++)
		{
			$google_xml = '<?xml version="1.0" encoding="utf-8"?>';
			$google_xml .= '<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">';
			$google_xml .= '<channel>';
			$google_xml .= '<title>360hqb.com - Online Store</title>';
			$google_xml .= '<link>http://www.360hqb.com</link>';
			$google_xml .= '<description>This is a 360hqb.com feed containing the required and recommended attributes for a variety of different products</description>';
			$rows = array_slice($goods, $i*$length, $length-1);
			if ( ! empty($rows))
			{
				foreach ($rows as $value)
				{
					$google_xml .= '<item>';
					$google_xml .= '<title>'.self::filter_title($value['goods_title']).'</title>';
					$google_xml .= '<link>'.$item_url.$value['goods_id'].'.html</link>';
					$summary = Items::get_goods_prop($value);
					$description = "";
					foreach ($summary as $key => $val)
					{
						$description .= $key.'：'.implode(' ',$val).' ';
					}

					$google_xml .= '<description>'.$description.'</description>';
					$google_xml .= '<g:id>'.$value['goods_id'].'</g:id>';
					$google_xml .= '<g:condition>new</g:condition>';
					$google_xml .= '<g:price>'.$value['retail_price'].'CNY</g:price>';
					$google_xml .= '<g:image_link>'.URL::image($value['image_md5'],'160','product').'</g:image_link>';

					// 获取品牌
					$main_name = "";
					preg_match_all('/(品牌:[^;]+)/', $value['props_str'], $matches);
					if ( is_array($matches[0]))
					{
						foreach ($matches[0] as $match)
						{
							if (stristr($match, '品牌') !== FALSE)
							{
								list( , $main_name) = explode(':', $match);
							}
						}
					}

					$google_xml .= '<g:brand>'.$main_name.'</g:brand>';

					$cat_path = DB::select('cat_path')
						->from('nav_cats_map')
						->where('cid', '=', $value['cid'])
						->fetch_one();

					$explode = explode(';', $cat_path);
					$cid = current($explode);

					$product_type = DB::select('title')
						->from('nav_cats_map')
						->where('catid', '=', $cid)
						->fetch_one();

					$google_xml .= '<g:product_type>'.$product_type.'</g:product_type>';
					$google_xml .= '</item>';
				}
			}

			$google_xml .= '</channel></rss>';
			$google_file = self::$_path.'360hqb_feed_'.$i.'.xml';
			file_put_contents($google_file, $google_xml);
		}
	}

	/**
	 * 过滤有关促销的字眼
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/9/19
	 */
	public static function filter_title($title)
	{
		//  替换逗号
		$title = str_replace(',', ' ', $title);

		// 过滤促销字眼
		$title = preg_replace('/[【|\[]?(打折|促销|降价|包邮|活动|秒杀|团购)[】|\]]?/', '', $title);

		return $title;
	}
}